package com.nnnu.orange.task;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.houbb.sensitive.word.core.SensitiveWordHelper;
import com.nnnu.orange.constant.StatusConstants;
import com.nnnu.orange.mapper.CommentsMapper;
import com.nnnu.orange.pojo.entity.Comments;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;


/**
 * 定时任务类定时审核评论
 */
@Slf4j
@RequiredArgsConstructor
@Component
public class CommentsTask {

    private final CommentsMapper commentsMapper;


    /**
     * 定时审核评论
     */
    @Scheduled(cron = "0 0 * * * ? ")
    public void reviewComments() {
        log.info("开始审核评论：{}", LocalDateTime.now());
        List<Comments> comments = commentsMapper.selectList(
                new LambdaQueryWrapper<Comments>().eq(Comments::getStatus, StatusConstants.ZERO));
        int reviewedCount = 0;
        int sensitiveCount = 0;
        if (!CollectionUtils.isEmpty(comments)) {
            for (Comments c : comments) {
                try {
                    if (SensitiveWordHelper.contains(c.getComment())) {
                        String newComment = SensitiveWordHelper.replace(c.getComment(), '*');
                        c.setComment(newComment).setStatus(StatusConstants.THREE);
                        sensitiveCount++;
                    } else {
                        c.setStatus(StatusConstants.ONE);
                    }
                    commentsMapper.updateById(c);
                    reviewedCount++;
                } catch (Exception e) {
                    log.error("审核评论失败，评论ID：{}", c.getCommentId(), e);
                }
            }
        }
        log.info("本次审核完毕，审核总数：{}，含敏感词数：{}", reviewedCount, sensitiveCount);
    }

}
